<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('客户资料共享')" />
	<style type="text/css">
		.layui-elem-quote{padding:5px;}
		hr{margin-bottom:0}
	</style>
</head>
<body>
<form class="layui-form" id="form-customer-add">
	<div th:style="${session.systemSet.sharedForCG}?'':'width:50%;float:left'">
		<blockquote class="layui-elem-quote">
			<input type="radio" name="bShared" value="1" title="完全共享" lay-filter="bSharedRadio" checked>
			<hr/>
		</blockquote>
	    <blockquote class="layui-elem-quote">
	    	<input type="radio" name="bShared" value="0" title="个别共享<span class='f_red'>（不填写数据默认不共享）</span>" lay-filter="bSharedRadio" th:checked="!${customerInfo?.bShared}">
	    	<hr/>
			<table class="layui-hide" id="dhtable" lay-filter="ftable"></table>
		</blockquote>
	</div>
	<div th:if="!${session.systemSet.sharedForCG}" style="width:50%;float:left">
		<table class="layui-hide" id="dhtable1" lay-filter="ftable1"></table>
	</div>
</form>
<th:block th:include="include :: footer" />
<script type="text/html" id="toolbar">
	<a class="layui-btn layui-btn-normal layui-table-tools dhicon dh-plus" lay-event="addBtn">&nbsp;新增</a>
	<a th:if="${session.systemSet.sharedForCG}" class="layui-btn layui-btn-normal layui-table-tools dhicon dh-plus" lay-event="swBtn">&nbsp;公共商务</a>
	<p th:if="${session.systemSet.sharedForCG}" style="display:inline-block"><span class="f_red">各销售对应商务中排首位的为默认商务</span></p>
</script>
<script type="text/html" id="toolbar1">
	<a class="layui-btn layui-btn-normal layui-table-tools dhicon dh-plus" lay-event="addBtn">&nbsp;新增</a>  
	<p th:if="${!session.systemSet.sharedForCG}" style="display:inline-block"><span class="f_red">排首位的为默认商务</span></p>
</script>
<script type="text/html" id="barDh">
    <a class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove" lay-event="del">&nbsp;删除</a>	         
</script>
<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix = ctx + "crm/customer";
	var session = [[${session}]];
	/*]]>*/
</script>
<script type="text/javascript">
var $,layer,form,table,listData,listData1,gridMap=[];
var gClient=window.location.href.split("=")[1];
layui.use(['table','form','layer','jquery'], function () {
    $ = layui.$,layer = layui.layer,form = layui.form,table = layui.table;
    if(session.systemSet.sharedForCG){//针对销售员设置客户商务
    	gridMap=[
	        {field: 'fOrder',title: '商务排序',width:80,edit:true},
        	{field: 'gClient',title: '客户编号',hide:true},
	        {field: 'gUser',title: '销售员编号',width:90},
	       	{field: 'gUserName',title: '销售员',width:90},
	       	{field: 'gUserDeptId',title: '部门编号',hide:true},
	       	{field: 'gUserDeptName',title: '部门'},
	       	{field: 'sUser',title: '商务员编号',width:90,event:'selectU',templet:function(d){
            	return  (d.sUser?d.sUser:'')+`<i class="layui-icon layui-icon-more" style="position: absolute;right: 10px;top: 9px;"></i>`;
        	}},
	       	{field: 'sUserName',title: '商务员',width:90},
	       	{field: 'sUserDeptId',title: '部门编号',hide:true},
	       	{field: 'sUserDeptName',title: '部门'},
	       	{title: '操作',templet:'#barDh',align:'center',width:80}
       	]
    }else{//未针对销售员设置客户商务
    	gridMap=[
	        {field: 'fOrder',title: '销售排序',width:80,edit:true},
        	{field: 'gClient',title: '客户编号',hide:true},
	       	{field: 'gUser',title: '销售员编号',width:90},
	       	{field: 'gUserName',title: '销售员',width:90},
	       	{field: 'gUserDeptId',title: '部门编号',hide:true},
	       	{field: 'gUserDeptName',title: '部门'},
	       	{title: '操作',templet:'#barDh',align:'center',width:80}
       	];
   		$.ajax({
   			url: prefix + '/sharedlist?sharedForCG=0&gUser=SW&gClient='+gClient,
   	        type: "get",
   	        dataType: "json",
   	        success: function(result){
   	        	$.tablelist.init({
   					elem: '#dhtable1'
   					,data: result.data
   	                ,page:false
   	                ,limit:10000
   	                ,cols: [[
   	          			{field: 'fOrder',title: '商务排序',width:80,edit:true},
	     	          	{field: 'gClient',title: '客户编号',hide:true},
	     	  	       	{field: 'sUser',title: '商务员编号',width:90},
	     	  	       	{field: 'sUserName',title: '商务员',width:90},
	     	  	       	{field: 'sUserDeptId',title: '部门编号',hide:true},
	     	  	       	{field: 'sUserDeptName',title: '部门'},
	     	  	       	{title: '操作',templet:'#barDh',align:'center',width:80}
	     	         	]
   	                ]
   					,toolbar: '#toolbar1'
   					,height:'full-10'
   					,done:function(res, curr, count){
   						listData1 = table.cache.dhtable1;//每次重载都赋值更新表缓存
   					}
   	            });
   	        }
   	  	});
    }
  	$.ajax({
		url: prefix + '/sharedlist?gClient='+gClient+'&sharedForCG='+(session.systemSet.sharedForCG?'1':'0&sUser=XS'),
        type: "get",
        dataType: "json",
        success: function(result){
        	$.tablelist.init({
				elem: '#dhtable'
				,data: result.data
                ,page:false
                ,limit:10000
                ,cols: [gridMap
                ]
				,toolbar: '#toolbar'
				,height:'full-115'
				,done:function(res, curr, count){
					listData = table.cache.dhtable;//每次重载都赋值更新表缓存
// 				    if($("[name='bShared']:checked").val()==1)$("[lay-id='dhtable']").hide();
				}
            });
        }
  	});
  	//监听工具条
	table.on('tool(ftable)', function (obj) {
		var data = obj.data, event = obj.event, tr = obj.tr,vIndex;//此处的data就是表格里面的值
        vIndex=$("tr").index(obj.tr)-1;
		switch(event){
			case "del":
				obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
				listData=table.cache.dhtable;
				for(var i=0; i < listData.length; i++)if(!listData[i] || listData[i].length==0)listData.splice(i, 1);//删除一项
				table.reload('dhtable',{data : listData});
				break;
			case "selectU":
				$.modal.open('选择员工-商务员','/system/user/select?roleType=SW',$(window).width()-200,$(window).height()-100,function(index){
			        var res = window["layui-layer-iframe" + index].callbackdata();
			        if(!!res){
			        	var r = [],flag=0;
			        	$.each(listData,function(i,v){
							if(v.LAY_TABLE_INDEX==vIndex){//缓存表内的下标和当前事件行下标的判断
								v['sUser']=res.userId;
								v['sUserName']=res.userName;
								v['sUserDeptId']=res.deptPath;
								v['sUserDeptName']=res.deptName;
								v['sharedForCG']=1;//可以弹出选择商务员的就是针对销售设置商务
							}
			        	});
			        	// 思路：获取没重复的最右一值放入新数组
						for(var i = 0, l = listData.length; i < l; i++) {
							for(var j = i + 1; j < l; j++)
						 		if (listData[i]['gUser'] == listData[j]['gUser'] && listData[i]['sUser'] == listData[j]['sUser']){
						 			flag=1;
						 			j = ++i;
						 		}
								r.push(listData[i]);
						}
						if(flag==1){
							layer.msg('出现重复，请重新选择！', {icon:7}, function(){
					        	table.reload('dhtable',{
					    			data : r
					    		});
					       	 	layer.closeAll();
							});
						}else{
							table.reload('dhtable',{
				    			data : r
				    		});
				       	 	layer.closeAll();
						}
			        }else{
			            layer.msg("请选择人员！", {icon:7});
			        }
			    });
				break;
		}
	});
	//监听工具条
	table.on('tool(ftable1)', function (obj) {
		var data = obj.data, event = obj.event, tr = obj.tr,vIndex;//此处的data就是表格里面的值
        vIndex=$("tr").index(obj.tr)-1;
		switch(event){
			case "del":
				obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
				listData1=table.cache.dhtable1;
				for(var i=0; i < listData1.length; i++)if(!listData1[i] || listData1[i].length==0)listData1.splice(i, 1);//删除一项
				table.reload('dhtable1',{data : listData1});
			break;
		}
	});
	//头部event事件
	table.on('toolbar(ftable)', function(obj){
	    switch(obj.event){
	    	case 'addBtn':
				$.modal.open('选择员工-销售员','/system/user/userselect?pagetype=checkbox',$(window).width()-200,$(window).height()-100,function(index){
			        var res = window["layui-layer-iframe" + index].callbackdata();
			        if(res.length > 0){
			        	$.each(res,function(i,v){
			        		var flag=true;//是否出现重复销售员
			        		var newData={};
			        		if(!session.systemSet.sharedForCG)$.each(listData,function(i2,v2){
			        			if(v.userId==v2.gUser)flag=false;
			        		})
			        		if(flag){
			        			newData={"gClient":gClient,"gUser":v.userId,"gUserName":v.userName,"gUserDeptId":v.deptPath,"gUserDeptName":v.deptName,"sharedForCG":0};
			        			if(!session.systemSet.sharedForCG)newData['sUser']="XS";
			        			if(listData.length > 0){
			    	    			if(listData[listData.length - 1]['fOrder']){
			    	    				newData['fOrder'] = Number(listData[listData.length - 1]['fOrder']) + 1;//行号自增1
			    	    			}else{
			    	    				newData['fOrder'] = 1;
			    	    			}
			    	    		}else{
			    	    			newData['fOrder'] = 1;
			    	    		}
			    	    		listData.push(newData);
			        		}
		        		});
			        	table.reload('dhtable',{data : listData});
			       	 	layer.closeAll();
			        }else{
			            layer.msg("请选择人员！", {icon:7});
			        }
			    });
	    		break;
	    	case 'swBtn':
	    		var newData={"gClient":gClient,"gUser":'public',"gUserName":'公共商务',"gUserDeptName":'服务客户所有销售',"sharedForCG":0};
	    		if(listData.length > 0){
	    			if(listData[listData.length - 1]['fOrder']){
	    				newData['fOrder'] = Number(listData[listData.length - 1]['fOrder']) + 1;//行号自增1
	    			}else{
	    				newData['fOrder'] = 1;
	    			}
	    		}else{
	    			newData['fOrder'] = 1;
	    		}
	    		listData.push(newData);
	    		table.reload('dhtable',{data : listData});
	    		break;
	    };
	});
	//头部event事件
	table.on('toolbar(ftable1)', function(obj){
	    switch(obj.event){
	    	case 'addBtn':
				$.modal.open('选择员工-商务员','/system/user/userselect?pagetype=checkbox',$(window).width()-200,$(window).height()-100,function(index){
			        var res = window["layui-layer-iframe" + index].callbackdata();
			        if(res.length > 0){
			        	$.each(res,function(i,v){
			        		var flag=true;//是否出现重复商务
			        		var newData={};
			        		$.each(listData1,function(i2,v2){
			        			if(v.userId==v2.sUser)flag=false;
			        		})
			        		if(flag){
			        			newData={"gClient":gClient,"gUser":"SW","sUser":v.userId,"sUserName":v.userName,"sUserDeptId":v.deptPath,"sUserDeptName":v.deptName,"sharedForCG":0};
			    	    		if(listData1.length > 0){
			    	    			if(listData1[listData1.length - 1]['fOrder']){
			    	    				newData['fOrder'] = Number(listData1[listData1.length - 1]['fOrder']) + 1;//行号自增1
			    	    			}else{
			    	    				newData['fOrder'] = 1;
			    	    			}
			    	    		}else{
			    	    			newData['fOrder'] = 1;
			    	    		}
			    	    		listData1.push(newData);
			        		}
		        		});
			        	table.reload('dhtable1',{data : listData1});
			       	 	layer.closeAll();
			        }else{
			            layer.msg("请选择人员！", {icon:7});
			        }
			    });
	    	break;
	    };
	});
	//共享设置单选框事件
  	form.on('radio(bSharedRadio)', function(data){
//   		if(data.value==1)$("[lay-id='dhtable']").hide();
//   		else $("[lay-id='dhtable']").show();
	}); 
 });
//提交调用的方法
function submitHandler() {
	if($("input[name='bShared']:checked").val()==1){
		$.operate.post(prefix + "/editpost", {'customerInfoItems':JSON.stringify([{'gClient':gClient,'bShared':1}], null, 2)});//修改客户信息
// 		if(session.systemSet.sharedForCG)$.operate.post(prefix + "/addsharedpost", {'gClient':gClient,'customerSharedItems':JSON.stringify([], null, 2)});
		if(session.systemSet.sharedForCG)$.operate.post(prefix + "/addsharedpost", {'gClient':gClient,'customerSharedItems':JSON.stringify(listData, null, 2)});
		else $.operate.post(prefix + "/addsharedpost", {'gClient':gClient,'customerSharedItems':JSON.stringify(listData1, null, 2)});
	}else{
		if(session.systemSet.sharedForCG){//销售指定商务
			if(listData.length){
				var flag=true;//是否填写商务员
				$.each(listData,function(k,v){
					if(!v['sUser'])flag=false;
				});
				if(flag){
					$.operate.post(prefix + "/editpost", {'customerInfoItems':JSON.stringify([{'gClient':gClient,'bShared':0}])},null,false);//修改客户信息
					$.operate.post(prefix + "/addsharedpost", {'gClient':gClient,'customerSharedItems':JSON.stringify(listData, null, 2)},null,false);
				}else{
					layer.msg("对应商务员未选择！");
				}
			}else{
				$.operate.post(prefix + "/editpost", {'customerInfoItems':JSON.stringify([{'gClient':gClient,'bShared':0}])},null,false);//修改客户信息
				$.operate.post(prefix + "/addsharedpost", {'gClient':gClient,'customerSharedItems':JSON.stringify(listData, null, 2)},null,false);//修改客户共享信息
			}
		}else{//销售、商务独立
			$.operate.post(prefix + "/editpost", {'customerInfoItems':JSON.stringify([{'gClient':gClient,'bShared':0}])},null,false);//修改客户信息
			$.operate.post(prefix + "/addsharedpost", {'gClient':gClient,'customerSharedItems':JSON.stringify(listData.concat(listData1), null, 2)},null,false);
		}
	}
}
</script>
</body>
</html>